local mKeyboard = {}
local const = require 'xLua.module.Keyboard.constant.kk'
xconst.keyboard = const

local press = eventpool:new( '键盘-按下' )
local release = eventpool:new( '键盘-松开' )

local map = {
    key_up = '键盘-松开',
    key_down = '键盘-按下',
}

--- [异步]注册热键
---@param eventNmae string 事件： 键盘-按下/key_down  键盘-松开/key_up
---@param combKey int 组合键，可以多个组合键相加 xconst.keyboard.COMB_
---@param key int 主要按键 xconst.keyboard.KEY_
---@param callback fun(event:event,params:table) 设置 params.ret = true 时拦截事件
---@return event
function mKeyboard:hotkey( eventNmae, combKey, key, callback )
    local params = {
        type = 'keyboard',
        combKey = combKey,
        key = key,
    }
    eventpool:reg( map[eventNmae] or eventNmae, params )
    ---@type event
    local event = params.ret
    if event then
        event.on_update = callback
    end
    return event
end

local genEvtName = function (comb,key)
    return comb .. '+' .. key
end

local msgHook = message.msgHook

local key_down = msgHook.key_down
msgHook.key_down = function (msg) --键盘按下事件  不会跟聊天框冲突
    local key = msg.code --整数 键码
    local comb = msg.state -- 组合键 默认为0

    local eventName = genEvtName( comb, key )

    local params = {
        combKey = comb,
        key = key,
    }
    press:update(eventName, params)

    --修改 msg.code 可以进行改键
    msg.state = params.combKey
    msg.code = params.key

    return key_down(msg) and not params.ret
end

local key_up = msgHook.key_up
msgHook.key_up = function (msg) --键盘松开事件  不会跟聊天框冲突
    local key = msg.code --整数 键码
    local comb = msg.state -- 组合键 默认为0

    local eventName = genEvtName( comb, key )

    local params = {
        combKey = comb,
        key = key,
    }
    release:update(eventName, params)

    --修改 msg.code 可以进行改键
    msg.state = params.combKey
    msg.code = params.key

    return key_up(msg) and not params.ret
end

--------------------------------
--          注册器
--------------------------------

local regPress = press:new('注册事件')
regPress.on_update = function (event, params)
    local comb = params.combKey
    local key = params.key
    local eventName = genEvtName( comb, key )
    params.ret = press:new( eventName )
end

local regRelease = release:new('注册事件')
regRelease.on_update = function (event, params)
    local comb = params.combKey
    local key = params.key
    local eventName = genEvtName( comb, key )
    params.ret = release:new( eventName )
end

return mKeyboard